<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('融资轮次')" prop="financingRound">
            <el-input v-model="form.financingRound" :placeholder="$t('融资轮次')" show-word-limit maxlength="20" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('融资方式')" prop="financingMode">
            <el-select v-model="form.financingMode" clearable filterable :placeholder="$t('融资方式')">
              <el-option
                v-for="dict in financingModeOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('融资日期')" prop="financingDate">
            <DatePicker v-model="form.financingDate" :placeholder="$t('融资日期')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('融资总金额') + $t('金额单位')" prop="financingTotalAmount">
            <Money v-model="form.financingTotalAmount" unit="w" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('融资前估值') + $t('金额单位')" prop="financingBeforeValuation">
            <Money v-model="form.financingBeforeValuation" unit="w" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('融资后估值') + $t('金额单位')" prop="financingAfterValuation">
            <Money v-model="form.financingAfterValuation" unit="w" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('币种')" prop="currency">
            <dict-select
              v-model="form.currency"
              dictionary="currency"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('公司类型')" prop="companyType">
            <dictSelect
              v-model="form.companyType"
              :clearable="true"
              dictionary="company_type"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="form.companyType === 'YXGS' ? $t('注册资本(万)') : $t('公司总股数(万股)')" prop="totalShare">
            <Money v-model="form.totalShare" unit="w" :placeholder="form.companyType === 'YXGS' ? $t('注册资本(万)') : $t('公司总股数(万股)')" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="area-header" style="margin-top: 10px">
        <span class="area-header-title">{{ $t('出资机构') }}</span>
      </div>
      <el-table tooltip-effect="darkTable" :data="form.companyInvestInstitutionList" border class="nowrapTable formTable">
        <el-table-column :label="$t('序号')" align="center" width="50">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('机构名称')" align="center" prop="institutionName">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('机构名称') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'companyInvestInstitutionList.' + scope.$index + '.institutionName'" :rules="investInstitutionRules.institutionName">
              <el-input v-model="scope.row.institutionName" :placeholder="$t('机构名称')" :disabled="!!scope.row.investorId" show-word-limit :maxlength="100" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('投资金额') + $t('金额单位')" align="center" prop="investAmount">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('投资金额') }}{{ $t('金额单位') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'companyInvestInstitutionList.' + scope.$index + '.investAmount'" :rules="investInstitutionRules.investAmount">
              <Money v-model="scope.row.investAmount" unit="w" :disabled="!!scope.row.investorId" :placeholder="$t('投资金额')" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('持股数量') + $t('(万股)')" align="center" prop="amount">
          <template slot-scope="scope">
            <money v-model="scope.row.shareholdingNumber" unit="w" :placeholder="$t('持股数量')" @change="shareholdingNumberChange($event, scope.$index)" />
          </template>
        </el-table-column>
        <el-table-column :label="$t('持股比例(%)')" align="center" prop="amount">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('持股比例(%)') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'companyInvestInstitutionList.' + scope.$index + '.shareholdingRatio'" :rules="investInstitutionRules.shareholdingRatio">
              <Ratio v-model="scope.row.shareholdingRatio" :placeholder="$t('持股比例(%)')" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('备注')" align="center" prop="remark" width="250">
          <template slot-scope="scope">
            <el-input v-model="scope.row.remark" :placeholder="$t('备注')" show-word-limit :maxlength="2000" :autosize="{ minRows: 2, maxRows: 4}" />
          </template>
        </el-table-column>
        <el-table-column :label="$t('操作')" align="center" width="80">
          <template slot-scope="scope">
            <el-button v-hasPermi="['company:finance:remove']" size="mini" type="text" icon="el-icon-delete" @click="delInvestInstitution(scope.$index)">{{ $t('删除') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="tol">
        <el-button v-hasPermi="['company:finance:edit']" type="primary" icon="el-icon-plus" size="mini" @click="addInvestInstitution">{{ $t("添加") }}</el-button>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <save-btn has-permi="company:finance" />
    </div>
  </div>
</template>

<script>
    import { saveCompanyFinance, getCompanyFinance, getLatestTotalShare } from '@/api/company/finance/companyFinance'
    import { findByCompanyId } from '@/api/deal/investment/dealInvestment'
    export default {
        data() {
            return {
                companyId: this.$route.query.companyId,
                // 融资轮次字典
                financingModeOptions: [], // 表单参数
                form: {},
                // 遮罩层
                loading: false,
                // 表单校验
                rules: {
                  financingRound: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], financingMode: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], financingDate: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], financingTotalAmount: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], financingAfterValuation: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], currency: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ]
                },
                investInstitutionRules: {
                  institutionName: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ],
                  shareholdingRatio: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ]
                }
            }
        },
      watch: {
        'form.companyInvestInstitutionList': {
          handler(newVal) {
            if (!this.form.id) {
              let totalAmount = 0
              let financeAfterValuation = 0
              newVal.forEach((item) => {
                totalAmount += item.investAmount ? item.investAmount : 0
                financeAfterValuation += item.shareholdingRatio
              })
              this.$set(this.form, 'financingTotalAmount', totalAmount === 0 ? undefined : totalAmount)
              console.log(financeAfterValuation)
              // this.$set(this.form, 'financingAfterValuation', (totalAmount / financeAfterValuation * 100) === 0 || (totalAmount / financeAfterValuation * 100) > 999000000000000 || !(totalAmount / financeAfterValuation * 100) ? undefined : totalAmount / financeAfterValuation * 100)
            }
          },
          deep: true
        }
      },
      created() {
        this.getDicts('financing_mode').then(response => {
          this.financingModeOptions = response.data
        })
      },
      mounted() {
        this.$bus.$emit('async_done')
      },
      methods: {
            // 初始化数据
            init(data) {
              this.loading = true
                if (data != null && data.id !== undefined) {
                    getCompanyFinance(data.id).then(response => {
                        this.form = response.data
                      this.loading = false
                    })
                } else {
                  this.reset()
                  const companyId = this.$route.query.companyId ? this.$route.query.companyId : this.$route.query.id
                  getLatestTotalShare(companyId).then(res => {
                    this.form.totalShare = res.data
                  })
                  findByCompanyId(companyId).then(res => {
                    res.data.forEach((item) => {
                      const row = {
                        id: undefined,
                        financeId: undefined,
                        dealId: item.dealId,
                        investorId: item.id,
                        institutionName: item.investorName,
                        investAmount: item.amountInvestmentFact,
                        shareholdingNumber: item.numberOfShares,
                        shareholdingRatio: item.latestShareholdingRatio,
                        remark: undefined
                      }
                      this.form.companyInvestInstitutionList.push(row)
                    })
                    this.loading = false
                  })
                }
            },
            // 表单重置
            reset() {
              this.form = {
                id: undefined,
                companyId: this.companyId,
                financingRound: undefined,
                companyType: undefined,
                financingMode: undefined,
                financingDate: undefined,
                financingTotalAmount: undefined,
                financingBeforeValuation: undefined,
                financingAfterValuation: undefined,
                currency: 'CNY',
                totalShare: undefined,
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                delFlag: undefined,
                companyInvestInstitutionList: []
              }
              this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                this.$parent.$parent.formOpen = false
                // 刷新list页面
                this.$parent.$parent.getList()
            },
            /** 提交按钮 */
            submitForm: function() {
                this.$refs['form'].validate(valid => {
                    if (valid) {
                        this.loading = true
                        saveCompanyFinance(this.form).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess(this.$t('保存成功'))
                                this.closeForm()
                            } else {
                                this.msgError(response.msg)
                            }
                            this.loading = false
                        })
                    } else {
                      this.locationError(document)
                    }
                })
           },
          // 删除出资机构
          delInvestInstitution(index) {
            this.form.companyInvestInstitutionList.splice(index, 1)
          },
          // 添加出资机构
          addInvestInstitution() {
            const row = {
              id: undefined,
              financeId: undefined,
              institutionName: undefined,
              investAmount: undefined,
              shareholdingNumber: undefined,
              shareholdingRatio: undefined,
              remark: undefined
            }
            if (!(this.form.companyInvestInstitutionList instanceof Array)) {
              this.$set(this.form, 'companyInvestInstitutionList', [])
            }
            this.$nextTick(() => {
              this.form.companyInvestInstitutionList.push(row)
            })
          },
          shareholdingNumberChange(val, index) {
            if (this.form.totalShare && val) {
              this.$set(this.form.companyInvestInstitutionList[index], 'shareholdingRatio', val / this.form.totalShare * 100)
            }
          }
        }

    }
</script>
